package com.zy.design.pattern.proxy;

import com.zy.design.pattern.proxy.base.IUser;
import com.zy.design.pattern.proxy.base.UserImp;
import com.zy.design.pattern.proxy.jdk.ProxyFactory;
import com.zy.design.pattern.proxy.rpc.IQuery;
import com.zy.design.pattern.proxy.rpc.client.BeanProxy;
import com.zy.design.pattern.proxy.rpc.server.ServerInstance;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyi
 * @date 2021/4/8 15:22
 * 代理模式应用场景
 * 1. 业务系统的非功能性需求开发
 * 比如：监控、统计、鉴权、限流、事务、幂等、日志
 * 2 代理模式在 RPC、缓存中的应用
 */
public class ProxyTest {

    public static void main(String[] args) throws InterruptedException {


        //基于JDK的动态代理 ------------
        System.out.println("------------基于JDK的动态代理------------");
        ProxyFactory proxyFactory = new ProxyFactory(new UserImp());
        IUser userProxy = (IUser) proxyFactory.getProxyInstance();

        System.out.println(userProxy.getName());
        userProxy.sayHello("代理类");
        System.out.println(userProxy.getClass());


        System.out.println("------------代理模式在RPC中应用------------");
        ServerInstance serverInstance = new ServerInstance(8080);
        new Thread(() -> {
            try {
                serverInstance.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        //等待服务器启动准备下
        TimeUnit.SECONDS.sleep(1);


        IQuery queryProxy = (IQuery) BeanProxy.getProxyBean(IQuery.class);
        String nameById = queryProxy.getNameById(1);
        System.out.println(nameById);

        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~");
        queryProxy.sayHello();

        TimeUnit.SECONDS.sleep(1);
        System.exit(0);


    }

}
